#include "monitor_ui.h"
#include "ui_monitor_ui.h"

#include <QVBoxLayout>
#include <QNetworkRequest>
#include <QDebug>


// 替换为你的 MJPG 流 URL
//const QString url = "http://192.168.0.57:8080/?action=stream";
monitor_ui::monitor_ui(const QString &url,QWidget *parent) :QWidget(parent),ui(new Ui::monitor_ui),frameProcessor(new FrameProcessor(url, this)), streamUrl(url)
{
    ui->setupUi(this);
    // QLabel 初始化
    ui->label_montior->setAlignment(Qt::AlignCenter);
    ui->label_montior->setText("Loading video stream...");
    ui->label_montior->setStyleSheet("background-color: black; color: white;");


    // 连接线程的信号到更新界面的槽
    connect(frameProcessor, &FrameProcessor::newFrame, this, &monitor_ui::updateFrame);
}

monitor_ui::~monitor_ui()
{
    delete ui;
    frameProcessor->stopProcessing();
    frameProcessor->wait();
}

void monitor_ui::updateFrame(const QImage &frame)
{
    // 更新 QLabel 图像
    ui->label_montior->setPixmap(QPixmap::fromImage(frame).scaled(ui->label_montior->size(), Qt::KeepAspectRatio));
}


//多线程
FrameProcessor::FrameProcessor(const QString &url, QObject *parent) : QThread(parent), url(url), manager(new QNetworkAccessManager(this)), running(true) {}

FrameProcessor::~FrameProcessor()
{
    stopProcessing();
    if (reply) {
        reply->abort();
        reply->deleteLater();
    }
}

void FrameProcessor::stopProcessing()
{
    QMutexLocker locker(&mutex);
    running = false;
}

void FrameProcessor::run()
{
    QNetworkRequest request(url);
    reply = manager->get(request);

    // 连接 readyRead 信号以处理数据
    connect(reply, &QNetworkReply::readyRead, [this]() {
        QMutexLocker locker(&mutex);
        if (!running) return;

        // 读取数据到缓冲区
        buffer.append(reply->readAll());

        // 查找完整的 JPEG 帧
        while (true) {
            int startIdx = buffer.indexOf("\xFF\xD8"); // JPEG SOI marker
            int endIdx = buffer.indexOf("\xFF\xD9", startIdx); // JPEG EOI marker

            if (startIdx != -1 && endIdx != -1 && endIdx > startIdx) {
                // 提取完整 JPEG 数据
                QByteArray jpegData = buffer.mid(startIdx, endIdx - startIdx + 2);
                buffer.remove(0, endIdx + 2);

                // 转换为 QImage
                QImage frame;
                if (frame.loadFromData(jpegData, "JPEG")) {
                    emit newFrame(frame);
                }
            } else {
                break; // 没有完整帧时退出
            }
        }
    });

    // 连接完成信号以结束处理
    connect(reply, &QNetworkReply::finished, [this]() {
        QMutexLocker locker(&mutex);
        if (!running) return;

        reply->deleteLater();
        reply = nullptr;

        // 停止线程
        running = false;
    });

    exec(); // 进入线程事件循环
}


void monitor_ui::on_pushButton_clicked()
{
    // 启动线程
    frameProcessor->start();
}
